package com.zby.admin.service.imp;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zby.admin.mapper.ReviewMapper;
import com.zby.admin.mapper.UserMapper;
import com.zby.admin.pojo.Review;
import com.zby.admin.pojo.dto.ReviewDto;
import com.zby.admin.pojo.vo.ReviewVo;
import com.zby.admin.pojo.User;
import com.zby.admin.service.ReviewService;
import com.zby.utils.Result;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import jakarta.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ReviewServiceImp extends ServiceImpl<ReviewMapper, Review> implements ReviewService {
    
    @Resource
    private ReviewMapper reviewMapper;
    
    @Resource
    private UserMapper userMapper;
    
    @Override
    public Result<ReviewVo> addReview(ReviewDto reviewDto) {
        // 参数校验
        if (reviewDto.getUserId() == null) {
            return Result.error(400, "用户ID不能为空");
        }
        
        if (reviewDto.getContent() == null || reviewDto.getContent().trim().isEmpty()) {
            return Result.error(400, "留言内容不能为空");
        }
        
        // 创建留言对象
        Review review = new Review();
        review.setUserId(reviewDto.getUserId());
        review.setContent(reviewDto.getContent());
        review.setProductId(reviewDto.getProductId());
        review.setParentId(reviewDto.getParentId() != null ? reviewDto.getParentId() : 0L);
        review.setCreateTime(LocalDateTime.now());
        review.setUpdateTime(LocalDateTime.now());
        
        // 保存留言
        boolean saved = this.save(review);
        if (!saved) {
            return Result.error(500, "留言发布失败");
        }
        
        // 转换为VO对象
        ReviewVo reviewVo = new ReviewVo();
        BeanUtils.copyProperties(review, reviewVo);
        
        return Result.success(reviewVo);
    }
    
    @Override
    public Result<Page<ReviewVo>> getReviewList(Integer page, Integer pageSize, Long productId) {
        // 分页查询
        Page<Review> reviewPage = new Page<>(page, pageSize);
        QueryWrapper<Review> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("deleted", 0);
        
        // 如果指定了商品ID，则查询该商品的留言
        if (productId != null) {
            queryWrapper.eq("product_id", productId);
        }
        
        // 按创建时间倒序排列
        queryWrapper.orderByDesc("create_time");
        
        Page<Review> resultPage = this.page(reviewPage, queryWrapper);
        
        // 转换为VO对象
        Page<ReviewVo> reviewVoPage = new Page<>();
        reviewVoPage.setCurrent(resultPage.getCurrent());
        reviewVoPage.setSize(resultPage.getSize());
        reviewVoPage.setTotal(resultPage.getTotal());
        
        List<ReviewVo> reviewVos = resultPage.getRecords().stream().map(review -> {
            ReviewVo reviewVo = new ReviewVo();
            BeanUtils.copyProperties(review, reviewVo);
            
            // 查询用户信息
            User user = userMapper.selectById(review.getUserId());
            if (user != null) {
                reviewVo.setUserNickname(user.getUserNickname());
                reviewVo.setUserProfilePictureSrc(user.getUserProfilePictureSrc());
            }
            
            return reviewVo;
        }).collect(Collectors.toList());
        
        reviewVoPage.setRecords(reviewVos);
        
        return Result.success(reviewVoPage);
    }
    
    @Override
    public Result<Boolean> deleteReview(Long reviewId) {

        if (reviewId == null) {
            return Result.error(400, "留言ID不能为空");
        }
        
        // 查找留言
        Review review = this.getById(reviewId);
        if (review == null) {
            return Result.error(404, "留言不存在");
        }
        
        // 逻辑删除留言
        boolean updated = removeById(reviewId);
        if (!updated) {
            return Result.error(500, "删除留言失败");
        }
        
        return Result.success(true);
    }
    
    @Override
    public Result<ReviewVo> getReviewById(Long reviewId) {
        if (reviewId == null) {
            return Result.error(400, "留言ID不能为空");
        }
        
        // 查找留言
        Review review = this.getById(reviewId);
        if (review == null) {
            return Result.error(404, "留言不存在");
        }
        
        // 转换为VO对象
        ReviewVo reviewVo = new ReviewVo();
        BeanUtils.copyProperties(review, reviewVo);
        
        // 查询用户信息
        User user = userMapper.selectById(review.getUserId());
        if (user != null) {
            reviewVo.setUserNickname(user.getUserNickname());
            reviewVo.setUserProfilePictureSrc(user.getUserProfilePictureSrc());
        }
        
        return Result.success(reviewVo);
    }
    
    @Override
    public Result<ReviewVo> updateReview(Long reviewId, ReviewDto reviewDto) {
        // 参数校验
        if (reviewId == null) {
            return Result.error(400, "留言ID不能为空");
        }
        
        if (reviewDto.getUserId() == null) {
            return Result.error(400, "用户ID不能为空");
        }
        
        if (reviewDto.getContent() == null || reviewDto.getContent().trim().isEmpty()) {
            return Result.error(400, "留言内容不能为空");
        }
        
        // 查找留言
        Review review = this.getById(reviewId);
        if (review == null) {
            return Result.error(404, "留言不存在");
        }
        
        // 更新留言对象
        review.setUserId(reviewDto.getUserId());
        review.setContent(reviewDto.getContent());
        review.setProductId(reviewDto.getProductId());
        review.setParentId(reviewDto.getParentId() != null ? reviewDto.getParentId() : 0L);
        review.setUpdateTime(LocalDateTime.now());
        
        // 保存更新
        boolean updated = this.updateById(review);
        if (!updated) {
            return Result.error(500, "留言更新失败");
        }
        
        // 转换为VO对象
        ReviewVo reviewVo = new ReviewVo();
        BeanUtils.copyProperties(review, reviewVo);
        
        return Result.success(reviewVo);
    }
    
    @Override
    public Result<Page<ReviewVo>> getReplyList(Long parentId, Integer page, Integer pageSize) {
        if (parentId == null) {
            return Result.error(400, "父级留言ID不能为空");
        }
        
        // 分页查询
        Page<Review> reviewPage = new Page<>(page, pageSize);
        QueryWrapper<Review> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("deleted", 0);
        queryWrapper.eq("parent_id", parentId);
        
        // 按创建时间倒序排列
        queryWrapper.orderByDesc("create_time");
        
        Page<Review> resultPage = this.page(reviewPage, queryWrapper);
        
        // 转换为VO对象
        Page<ReviewVo> reviewVoPage = new Page<>();
        reviewVoPage.setCurrent(resultPage.getCurrent());
        reviewVoPage.setSize(resultPage.getSize());
        reviewVoPage.setTotal(resultPage.getTotal());
        
        List<ReviewVo> reviewVos = resultPage.getRecords().stream().map(review -> {
            ReviewVo reviewVo = new ReviewVo();
            BeanUtils.copyProperties(review, reviewVo);
            
            // 查询用户信息
            User user = userMapper.selectById(review.getUserId());
            if (user != null) {
                reviewVo.setUserNickname(user.getUserNickname());
                reviewVo.setUserProfilePictureSrc(user.getUserProfilePictureSrc());
            }
            
            return reviewVo;
        }).collect(Collectors.toList());
        
        reviewVoPage.setRecords(reviewVos);
        
        return Result.success(reviewVoPage);
    }
    
    @Override
    public Result<List<ReviewVo>> getReviewsByProductId(Long productId) {
        if (productId == null) {
            return Result.error(400, "商品ID不能为空");
        }
        
        // 查询指定商品的所有评论
        QueryWrapper<Review> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("deleted", 0);
        queryWrapper.eq("product_id", productId);
        
        // 按创建时间倒序排列
        queryWrapper.orderByDesc("create_time");
        
        List<Review> reviews = this.list(queryWrapper);
        
        // 转换为VO对象列表
        List<ReviewVo> reviewVos = reviews.stream().map(review -> {
            ReviewVo reviewVo = new ReviewVo();
            BeanUtils.copyProperties(review, reviewVo);
            
            // 查询用户信息
            User user = userMapper.selectById(review.getUserId());
            if (user != null) {
                reviewVo.setUserNickname(user.getUserNickname());
                reviewVo.setUserProfilePictureSrc(user.getUserProfilePictureSrc());
            }
            
            return reviewVo;
        }).collect(Collectors.toList());
        
        return Result.success(reviewVos);
    }
    

}